<template>
  <div class="main__content">
    <n-layout has-sider sider-placement="right">
      <n-layout-content>
        <GISMap ref="gisMap" class="content__map" :param="routeParam" :accident-video="accidentVideo" @coords="getCoords" @polygon="getPolygon" @completed="handleCompleted" />
        <VideoModal
          v-if="videoShow"
          v-model:visible="videoShow"
          :options="liveOptions"
          :airport-info="airportInfo"
          :drone-msg="droneMsg"
          :airport-msg="airportMsg"
          :airport-url="airportUrl"
          class="content__video"
        />
      </n-layout-content>
      <n-layout-sider
        collapse-mode="width"
        :collapsed-width="0"
        :width="350"
        :native-scrollbar="false"
        show-trigger="arrow-circle"
      >
        <SidePanel
          ref="sidePanelRef"
          class="content__side"
          :ques-list="quesList"
          @done="handleDone"
          @selected="handleSelect"
          @ignore="ignoreAccident"
        />
      </n-layout-sider>
    </n-layout>
  </div>
</template>

<script>
import GISMap from '@/views/gisMap/index.vue'
import VideoModal from './components/VideoModal.vue'
import SidePanel from './components/SidePanel.vue'
import { getAirportMsg, getAirportDetail, getAirportUrl, createTask, routeByAccident, routeByTask , routeByline } from '@/api/dashboard/index.js'
import { getFlightData } from '@/api/flight-data/index.js'
import SocketService from '@/utils/websocket.js'
import { useUserStore } from '@/store/modules/user.js'
import { formatDateTime } from '@/utils/index.js'
import { ref, reactive, toRefs, onMounted, onUnmounted, nextTick, provide } from 'vue'
export default {
  name: 'DashboardPage',
  components: { GISMap, VideoModal, SidePanel },
  setup() {
    const sidePanelRef = ref()
    const gisMap = ref()
    const userStore = useUserStore()
    const data = reactive({
      timer: null,
      times: 0,
      airportSocket: SocketService.Instance,
      quesList: [],
      airport: null,
      airportInfo: {},
      droneMsg: {},
      airportMsg: {},
      airportUrl: null,
      bufferAirportId: null,
      routeParam: null,
      routeCoords: [],
      polygonCoords: [],
      regionList: [], // 区域经纬度列表
      airportLngLat: [],
      airportRouteList: [],
      accidentLayer: null,
      // 飞行轨迹相关
      trackInfo: null,
      accidentVideo: null,
      counter: 0
    })

    const video = reactive({
      videoShow: false,
      liveOptions: {}
    })
    /**
     * @description: 选中面板的数据
     * @return {*}
     */
    const handleSelect = (info) => {
      const { tabType, id, airportId, droneId, status, refresh = false } = info
      data.airportInfo = info
      if (!refresh) {
        video.videoShow = tabType === 'task' && id
        gisMap.value.clearTrack()
        if (tabType === 'task') {
          clearDraw()
          if (data.accidentLayer !== null) {
            gisMap.value.removeLayer(data.accidentLayer)
            gisMap.value.hideAccidentInfo()
          }
          // 初始化画航线
          if (!data.airportInfo?.accidentId && data.airportInfo?.id) {
            routeByTask(data.airportInfo?.id).then(res => {
              if (res.code === 0) {
                if (res.data?.length) {
                  gisMap.value.drawDroneRoute(res.data)
                }
              }
            })
          }
        } else if (tabType === 'ques') {
          if (data.accidentLayer !== null) {
            gisMap.value.removeLayer(data.accidentLayer)
            gisMap.value.hideAccidentInfo()
          }
          if (info?.id) {
            data.accidentLayer = gisMap.value.addAccident(info)
          }
        }
      }
      if (video.videoShow) {
        if (status !== 10) {
          fetchAirportUrl(droneId)
        }
        if (status === 10) {
          fetchAirportMsg(id)
        } else {
          fetchAirportDetail(airportId)
        }
      }
    }

    const fetchAirportMsg = async(droneId) => {
      const res = await getAirportMsg(droneId)
      if (res.code === 0) {
        data.droneMsg = res.data
      } else {
        data.droneMsg = {}
      }
    }
    const fetchAirportDetail = async(airportId) => {
      const res = await getAirportDetail(airportId)
      if (res.code === 0) {
        data.airportMsg = res.data
      } else {
        data.airportMsg = {}
      }
    }

    const fetchAirportUrl = async(id) => {
      const res = await getAirportUrl(id)
      if (res.code === 0 && res.data.records.length) {
        const { externalMonitorUrl } = res.data.records[0]
        data.airportUrl = externalMonitorUrl
      } else {
        data.airportUrl = null
      }
    }

    /**
     * 忽略事故,删除事故图层
     */
    const ignoreAccident = () => {
      if (data.accidentLayer !== null) {
        gisMap.value.removeLayer(data.accidentLayer)
        data.accidentLayer = null
        gisMap.value.hideAccidentInfo()
      }
    }

    const clearDraw = () => {
      // 清除新建事故中的机场缓冲区和绘制区域
      gisMap.value.clearAirportBuffer()
      gisMap.value.clearRoute()
      gisMap.value.clearDrawGeometry()
      data.bufferAirportId = null
      data.airportLngLat = []
      data.airportRouteList = []
    }

    const handleDone = (info) => {
      if (Object.keys(info).length) {
      // 绘制机场覆盖范围缓冲区
        if (info?.airportId) {
          if (info?.airportId !== data.bufferAirportId) {
            data.bufferAirportId = info?.airportId
            data.airportLngLat = [parseFloat(info?.longitude), parseFloat(info?.latitude)]
            // data.airportLngLat = [parseFloat(info?.longitude), parseFloat(info?.latitude)]
            gisMap.value.drawAirportBuffer(data.airportLngLat, info?.coverage)
            if (info?.operate !== 'save' & info?.lineType !== null) {
              gisMap.value.drawGeometry(info?.lineType)
            }
          }
        }
        // 绘制模式
        if (info?.operate !== 'save' & info?.key === 'lineType') {
          gisMap.value.drawGeometry(info?.lineType)
        }
        if (info?.key === 'interval' || info?.key === 'angle') {
          data.routeParam = {
            interval: info?.interval,
            angle: info?.angle
          }
        }
        // 保存
        if (info?.operate === 'save') {
          if (data.routeCoords?.length) {
            data.airportRouteList = []
            data.regionList = []
            let lineType
            if (info?.lineType === 'Point') {
              data.routeCoords.map(item => {
                data.airportRouteList.push({
                  altitude: info?.altitude,
                  lng: data.airportLngLat[0],
                  lat: data.airportLngLat[1]
                })
                data.airportRouteList.push({
                  altitude: info?.altitude,
                  lng: item[0],
                  lat: item[1]
                })
                data.airportRouteList.push({
                  altitude: info?.altitude,
                  lng: data.airportLngLat[0],
                  lat: data.airportLngLat[1]
                })
                data.regionList.push({
                  lng: item[0],
                  lat: item[1]
                })
              })
              lineType = 1
            } else if (info?.lineType === 'LineString') {
              data.airportRouteList.push({
                altitude: info?.altitude,
                lng: data.airportLngLat[0],
                lat: data.airportLngLat[1]
              })
              data.routeCoords.map(item => {
                data.airportRouteList.push({
                  altitude: info?.altitude,
                  lng: item[0],
                  lat: item[1]
                })
                data.regionList.push({
                  lng: item[0],
                  lat: item[1]
                })
              })
              data.airportRouteList.push({
                altitude: info?.altitude,
                lng: data.airportLngLat[0],
                lat: data.airportLngLat[1]
              })
              lineType = 2
            } else {
              data.airportRouteList.push({
                altitude: info?.altitude,
                lng: data.airportLngLat[0],
                lat: data.airportLngLat[1]
              })
              data.routeCoords.map(item => {
                data.airportRouteList.push({
                  altitude: info?.altitude,
                  lng: item[0],
                  lat: item[1]
                })
              })
              data.polygonCoords.map(item => {
                data.regionList.push({
                  lng: item[0],
                  lat: item[1]
                })
              })
              data.airportRouteList.push({
                altitude: info?.altitude,
                lng: data.airportLngLat[0],
                lat: data.airportLngLat[1]
              })
              lineType = 3
            }
            const params = {
              airportRouteList: data.airportRouteList,
              accidentRegionList: data.regionList,
              questionCode: info?.questionCode,
              questionId: info?.questionId,
              droneId: info?.droneId,
              airportId: info?.airportId,
              legId: info?.legId,
              dspServiceInstId: info?.dspServiceInstId,
              lineType: lineType,
              channelId: info?.channelId
            }
            createTask(params).then(res => {
              if (res.code === 0) {
                clearDraw()
                sidePanelRef.value.handleSave()
              }
            })
          } else {
            $message.error('请先绘制!')
          }
        }
      } else {
        clearDraw()
      }
    }

    const getCoords = (lngLats) => {
      data.routeCoords = lngLats
    }

    const getPolygon = (lngLats) => {
      data.polygonCoords = lngLats
    }

    const handleCompleted = (id) => {
      console.log(id)
    }

    onMounted(() => {
      const timestamp = new Date().getTime()
      data.airportSocket.connect(`${userStore.userInfo.username}:${timestamp}`)
      nextTick(() => {
        sidePanelRef.value.queryTaskList()
        data.timer = setInterval(() => {
          data.times++
          if (data.times % 5 === 0) {
            sidePanelRef.value.queryTaskList()
          }
          if (data.times % 1 === 0) {
            // 只展示日常巡检的航线和飞行轨迹
            if (data.airportInfo?.tabType === 'task') {
              if (!data.airportInfo?.accidentId && data.airportInfo?.id) {
                if (data.airportInfo?.status === 10) {
                  getFlightData(data.airportInfo?.id).then(res => {
                    if (res.code === 0) {
                      gisMap.value.drawTrack(res.data)
                    }
                  })
                }
              }
            } else if (data.airportInfo?.tabType === 'ques') {
              if (data.airportInfo?.inspectionId || data.airportInfo?.accidentInspectionId) {
                if (data.airportInfo?.inspectionStatus === 10) {
                  if (data.counter === 0) {
                    data.accidentVideo = data.airportInfo?.emergencyInspectionAiPullUrl ? data.airportInfo?.emergencyInspectionAiPullUrl : (data.airportInfo?.originalInspectionAiPullUrl || null)
                  }
                  getFlightData(data.airportInfo?.accidentInspectionId ? data.airportInfo?.accidentInspectionId : data.airportInfo?.inspectionId).then(res => {
                    if (res.code === 0) {
                      gisMap.value.drawTrack(res.data)
                    }
                  })
                }
              }
            }
          }
        }, 1000)
        const { ws } = data.airportSocket
        ws.onmessage = (msg) => {
          const list = JSON.parse(msg.data)
          list.forEach((item) => {
            item.formatTime = formatDateTime(item.createTime)
          })
          if (Object.keys(data.airportInfo).length) {
            const info = list.find((item) => item.id === data.airportInfo?.id) || {}
            if (Object.keys(info).length) {
              if (info) {
                data.counter++
                data.accidentVideo = info?.emergencyInspectionAiPullUrl ? info?.emergencyInspectionAiPullUrl : (info?.originalInspectionAiPullUrl || null)
              }
            }
          }
          data.quesList = list
        }
      })
    })

    onUnmounted(() => {
      clearInterval(data.timer)
      data.timer = null
      data.times = 0
    })

    return {
      ...toRefs(data),
      ...toRefs(video),
      ...toRefs(data),
      sidePanelRef,
      gisMap,
      handleSelect,
      handleDone,
      getCoords,
      getPolygon,
      handleCompleted,
      ignoreAccident
    }
  }
}

</script>
<style scoped lang='scss'>
.wrapper {
  background: rgba(240, 242, 245, 1);
}

::v-deep(.n-scrollbar-container){
  .n-scrollbar-content{
    height: 100%;
  }
}

.main__content {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  .content__map{
    // width: calc(100% -  240px);
  }
  ::v-deep(.n-layout-scroll-container){
    position: relative;
    .content__video{
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 999;
    }
  }
  .content__side{
    width: 350px;
    height: 100%;
    box-sizing: border-box;
  }
}
</style>
